package com.gitee.wsl.jvm.net.security.token

import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.time.Instant

/**
 * A simple [TokenStorage] that uses `DataStore` to store [AuthenticationResponse] for reuse across
 * app sessions.
 */
interface TokenStorage {
    /** Updates the current stored auth data. */
    suspend fun updateAuthData(authData: AuthenticationData)
    /** Returns the current auth data or null if none are stored. */
    suspend fun getAuthData(): AuthenticationData?
}

data class AuthenticationData(val tokenType: String, val expiration: Instant, val token: String)

@JsonClass(generateAdapter = true)
data class AuthenticationResponse(
    @Json(name = "token_type") val tokenType: String,
    @Json(name = "expires_in") val expiresIn: Long,
    @Json(name = "access_token") val accessToken: String,
)

suspend fun TokenStorage.updateAuthData(response: AuthenticationResponse) {
    updateAuthData(
        AuthenticationData(
            response.tokenType,
            Instant.now().plusSeconds(response.expiresIn),
            response.accessToken
        )
    )
}